"use strict";

const { Controller } = require("../core/controller");
const jwt = require("jsonwebtoken");

class SystemController extends Controller {
  async login() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;
    console.log({ username, password });
    try {
      const rules = {
        username: { type: "string", required: true, message: "请输入账号" },
        password: { type: "string", required: true, message: "请输入密码" },
      };
      await ctx.validate(rules, ctx.request.body);
      const user = await ctx.service.user.checkUser(username, password);
      if (user) {
        // 生成 Token
        const token = jwt.sign({ uid: user.id }, this.app.config.jwt.secret, {
          expiresIn: this.app.config.jwt.expiresIn,
        });
        // 返回成功响应
        ctx.status = 200;
        this.success({ token });
      } else {
        // 返回错误信息
        ctx.throw(401, "用户名或密码不正确");
      }
    } catch (err) {
      console.log(err);
      // 验证失败，处理错误
      this.fail(err.message);
    }
  }
  async logout() {
    this.result(200, "退出成功");
  }
}

module.exports = SystemController;
